package com.gzhryc.shared_device.oem.micro.api.controllers.xcx.v1.pcl;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.common.device.dao.db.Device;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.oem.code.device.EDeviceFunCode;
import com.gzhryc.shared_device.oem.code.member.LoginMember;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceBusinessConfig;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.services.PlaceBusinessConfigService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.micro.api.MicroConstants;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.pcl.PCLScanGetRequest;
import com.gzhryc.shared_device.oem.micro.api.dto.xcx.v1.pcl.PCLScanGetResponse;
import com.gzhryc.shared_device.pcl.code.dao.db.ChargingCable;
import com.gzhryc.shared_device.pcl.code.dao.db.PCLFeeTemplate;
import com.gzhryc.shared_device.pcl.code.dao.db.PCLOrder;
import com.gzhryc.shared_device.pcl.code.dao.enums.ChargingCableEnum;
import com.gzhryc.shared_device.pcl.code.dao.models.SetMealContent;
import com.gzhryc.shared_device.pcl.code.services.ChargingCableService;
import com.gzhryc.shared_device.pcl.code.services.PCLFeeTemplateService;
import com.gzhryc.shared_device.pcl.code.services.PCLOrderService;

public class PCLScanController {

    static Logger log = Logger.getLogger(PCLScanController.class);

    @Route(value = { "/xcx/v1/pcl/scan/get.do" }, method = "POST")
    public PCLScanGetResponse getSharedDevice(HttpServletRequest request) {
        PCLScanGetResponse apiResp = new PCLScanGetResponse(ClientAPICodeConstants.NULL_DATA, "未找到设备信息");
        PCLScanGetRequest apiReq = WebUtils.getJsonRequest(request, PCLScanGetRequest.class);
        if (apiReq != null && StringUtils.isNotBlank(apiReq.getBody().getDeviceSn())) {
            String deviceSn = apiReq.getBody().getDeviceSn().trim();
            LoginMember member = WebUtils.getAttribute(request, MicroConstants.ATTR_LOGIN_MEMBER, LoginMember.class);
            Device device = DeviceService.self().getByDeviceSn(deviceSn);
            if (device == null || device.getPlaceId() == null) {
                log.error("未找到{{0}}设备或未部署",deviceSn);
                return apiResp;
            }

            ChargingCable chargingCable = ChargingCableService.self().getByDeviceSn(deviceSn);
            if (chargingCable == null) {
                log.error("未找到{{0}}设备",deviceSn);
                return apiResp;
            }

            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
            apiResp.getBody().setDeviceSn(device.getDeviceSn());
            apiResp.getBody().setState(chargingCable.getState());

            if(ChargingCableEnum.State.Working.index().equals(chargingCable.getState())){
                PCLOrder pclOrder = PCLOrderService.self(chargingCable.getLastWorkDate()).getByTradeNo(chargingCable.getCurrentTradeNo());
                if(pclOrder != null && pclOrder.getMemberId().equals(member.getId())){
                    apiResp.getBody().setTradeNo(pclOrder.getTradeNo());
                    apiResp.getBody().setWorkDate(pclOrder.getCreateDate());
                    return apiResp;
                }
            }

            PCLFeeTemplate feeTemplate = null;
            PlaceBusinessConfig deviceFunc = PlaceBusinessConfigService.self().getByKeys(device.getPlaceId(), EDeviceFunCode.PCL.index());
            if(deviceFunc != null && deviceFunc.getFeeTemplateId() != null) {
                feeTemplate = PCLFeeTemplateService.self().getById(deviceFunc.getFeeTemplateId());
            }

            if(feeTemplate == null){
                Long userId = device.getUserId();
                if(userId == null){
                    PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(device.getPlaceId());
                    if(physicalStore != null){
                        userId = physicalStore.getUserId();
                    }
                }
                feeTemplate = PCLFeeTemplateService.self().getNewByKeys(userId,device.getDeviceTypeId());
                if(feeTemplate == null){
                    //获取平台默认模版
                    feeTemplate = PCLFeeTemplateService.self().getNewByKeys(0L,device.getDeviceTypeId());
                }
            }

            if(feeTemplate != null && StringTools.isNotBlank(feeTemplate.getSetMealContent())){
                SetMealContent setMealContent = JsonTools.fromJson(feeTemplate.getSetMealContent(),SetMealContent.class);
                if(setMealContent != null && setMealContent.getItems().size() > 0) {
                    apiResp.getBody().setTemplateId(feeTemplate.getId());
                    apiResp.getBody().setFreeItems(new ArrayList<>());
                    for(SetMealContent.Item item : setMealContent.getItems()){
                        PCLScanGetResponse.FreeItem freeItem = new PCLScanGetResponse.FreeItem();
                        freeItem.setId(item.getId());
                        freeItem.setName(item.getName());
                        freeItem.setTimes(item.getTimes());
                        freeItem.setMoneyStr(item.getMoneyStr());
                        apiResp.getBody().getFreeItems().add(freeItem);
                    }
                }
            }
        }
        return apiResp;
    }
}
